extends Control

signal dialog_finished

@onready var text_label = $Background/MarginContainer/Text
@onready var background = $Background
@onready var pointer = $Background/Pointer

var current_text: String = ""
var display_speed: float = 0.1  # 增加到0.1秒每个字符
var char_index: int = 0
var is_typing: bool = false
var timer: float = 0.0  # 添加计时器变量
var can_continue: bool = false  # 添加标记，表示是否可以继续下一句

func _ready():
	hide()
	set_process(false)

func _input(event):
	if visible and event.is_action_pressed("mouse_left"):  # 移除 ui_accept 检查
		if is_typing:  # 如果正在打字，立即显示完整文本
			text_label.text = current_text
			is_typing = false
			can_continue = true
			set_process(false)
		elif can_continue:  # 如果已经显示完整文本，发送完成信号
			hide()
			dialog_finished.emit()

func update_pointer_position():
	# 等待一帧让文本更新并重新布局
	await get_tree().process_frame
	# 更新箭头位置到底部中心
	pointer.position.x = background.size.x / 2
	pointer.position.y = background.size.y

func show_dialog(text: String, _duration: float = 2.0):
	show()
	current_text = text
	text_label.text = ""
	char_index = 0
	is_typing = true
	can_continue = false
	set_process(true)
	
	# 调整对话框宽度
	var min_width = 120  # 最小宽度
	var max_width = 300  # 最大宽度
	var text_width = text.length() * 15  # 根据文本长度估算宽度
	var target_width = clamp(text_width, min_width, max_width)
	
	# 设置背景面板的自定义最小大小
	background.custom_minimum_size.x = target_width
	
	# 更新指针位置
	update_pointer_position()

func _process(delta):
	if is_typing and char_index < current_text.length():
		timer += delta
		if timer >= display_speed:  # 当计时器达到显示速度时
			text_label.text += current_text[char_index]
			char_index += 1
			timer = 0.0  # 重置计时器
			
			# 每次添加文字后更新指针位置
			update_pointer_position()
			
			if char_index >= current_text.length():
				is_typing = false
				can_continue = true
				set_process(false)

# 更新位置以跟随目标
func update_position(target_position: Vector2, is_player: bool = false):
	# 设置对话框位置，使其显示在目标上方
	global_position = target_position
	global_position.y -= 35 if not is_player else 45  # 使用固定偏移值
	global_position.x = target_position.x  # 保持水平居中
